# 1.python和mysql交互

# 1.安装 pip install pymysql

import pymysql


# 增加数据
def python_mysql():
    try:
        connect = pymysql.Connect(
            host="localhost",
            port=3306,
            db="newdb",
            user="root",
            passwd="1",
            charset="utf8"
        )

        # 2. 游标操作对象
        cursor = connect.cursor()

        # 1.增加
        # insert_sql = "insert into stu(name) values('python小伙')"
        # result = cursor.execute(insert_sql)
        # print(result)

        # 2.删除
        # delete_sql = "delete from stu where id=9"
        # result = cursor.execute(delete_sql)
        # print(result)

        # 3.改
        # update_sql = "update stu set name='新人' WHERE id=1"
        # result = cursor.execute(update_sql)
        # print(result)


        # 系统 手动输入学生信息
        # stu_name = input("请输入学生的名字:")
        # stu_gender = int(input("请输入学生的性别:"))
        #
        # add_sql = 'insert into stu(name,gender) values(%s,%s)'
        # params = [stu_name,stu_gender]
        # cursor.execute(add_sql, params)


        # 查询语句 一条语句 返回一个元组
        # find_sql = "select * from stu where id=4"
        # cursor.execute(find_sql)
        # result = cursor.fetchone()

        # 查询多条语句, 返回一个大元组包含小元组
        # find_sql = "select * from stu where id<4"
        # cursor.execute(find_sql)
        # result = cursor.fetchall()
        # print(result)

        create_table = "create table newdb2(id int auto_increment primary KEY);"
        cursor.execute(create_table)

        # 每个操作语句 都要提交事务
        connect.commit()
        # 关闭cursor
        cursor.close()
        # 关闭连接
        connect.close()
    except Exception as e:
        print(e.message)

python_mysql()
